package com.jchao.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jchao.auth.mapper.SysRoleMapper;
import com.jchao.auth.service.SysUserRoleService;
import com.jchao.auth.service.SysRoleService;
import com.jchao.model.system.SysRole;
import com.jchao.model.system.SysUserRole;
import com.jchao.vo.system.AssginRoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * create 2023/11/13 22:47
 */

@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Autowired
    private SysUserRoleService userRoleService;
    @Override
    public Map<String, Object> findRoleByAdminId(Long userId) {
       List<SysRole> assginRoleList=userRoleService.findRoleByAdminId(userId);
        List<SysRole> allRolesList = this.list();
        Map<String, Object> roleMap = new HashMap<>();
        roleMap.put("assginRoleList", assginRoleList);
        roleMap.put("allRolesList", allRolesList);
        return roleMap;
    }

    @Transactional
    @Override
    public void doAssign(AssginRoleVo assginRoleVo) {
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId, assginRoleVo.getUserId());
        userRoleService.remove(wrapper);
        ArrayList<SysUserRole> list = new ArrayList<>();
        List<Long> roleIdList = assginRoleVo.getRoleIdList();
        Long userId = assginRoleVo.getUserId();
        for (Long roleId : roleIdList) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(roleId);
            sysUserRole.setUserId(userId);
            list.add(sysUserRole);
        }
        userRoleService.saveBatch(list);
    }
}
